package com.quyeying.controller;

import com.quyeying.utils.OssUtil;
import com.quyeying.utils.result.R;
import com.quyeying.utils.result.ResultEnum;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;
import java.io.IOException;
import java.io.InputStream;
import java.util.UUID;

/**
 * @ClassName UploadController
 * @Description TODO
 * @Author Jll
 * @Date 2022/7/26 9:34
 * @Version 1.0
 */
@RestController("/")
@Slf4j
public class UploadController {

    @Resource
    private OssUtil ossUtil;

    /**
     * 文件上传
     * @param file
     * @return
     */
    @PostMapping("/file/upload")
    public R upload(MultipartFile file) {
        String filename = file.getResource().getFilename();
        //这里文件名用了uuid 防止重复，可以根据自己的需要来写
        String name = UUID.randomUUID() + filename.substring(filename.lastIndexOf("."), filename.length());
        name = name.replace("-", "");
        InputStream inputStream = null;
        try {
            inputStream = file.getInputStream();
        } catch (IOException e) {
            e.printStackTrace();
            R.error(ResultEnum.SYSTEM_ERROR);
        }

        //上传成功返回完整路径的url
        String url = ossUtil.upload(inputStream, name);
        log.info("上传内容七牛云回调++++++++++++++++++++++"+url);
        return R.success(url);
    }

    /**
     * 客户端上传需要的token
     * @return
     */
    @GetMapping("/file/getToken")
    public R getToken(){
        return R.success(ossUtil.getToken());
    }
}
